package com.tmt.im.common.yunxin.impls;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.im.common.Constant;
import com.tmt.im.common.yunxin.ErrorCode;
import com.tmt.im.common.yunxin.IYunXinConfig;
import com.tmt.im.common.yunxin.IYunXinMsgSender;
import com.tmt.im.common.yunxin.YunXinHelper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/24 11:41
 * @Version 1.0
 **/
@Order(0)
public class DefaultYunXinMsgSender_V9 implements IYunXinMsgSender, ApplicationContextAware {

    private static final String SEND_CUSTOMIZED_MESSAGE_URL = "https://api.netease.im/nimserver/msg/sendAttachMsg.action";
    private static final String SEND_CHAT_MSG_URL = "https://api.netease.im/nimserver/msg/sendMsg.action";

    private IYunXinConfig yunXinConfig;

    @Override
    public boolean sendCustomizedMsg(Long from, Long to, JSONObject content, StringBuilder error) {
        try {
            MultiValueMap<String, Object> reqParam = new LinkedMultiValueMap<>();
            reqParam.add("from", "" + from);
            reqParam.add("to", "" + to);
            reqParam.add("msgtype", 0);
            reqParam.add("attach", content.toJSONString());
            JSONObject jsonObject = YunXinHelper.exchange(SEND_CUSTOMIZED_MESSAGE_URL, HttpMethod.POST, reqParam, yunXinConfig);
            Long code = jsonObject.getLong("code");
            if (code == 200L) {
                return true;
            }
            throwExceptionByCode(code, jsonObject);
        } catch (Exception ex) {
            error.append(ex.getMessage());
        }
        return false;
    }

    /**
     * 云信V9版本的消息发送接口。
     *
     * @param senderId
     * @param receiverId
     * @param msgType    0：文本消息  1：图片消息 2：语音消息  3：视频消息 4：地理位置消息 6：文件消息 10：提示消息 100：自定义消息
     * @param msg
     * @param error
     * @return
     */
    @Override
    public boolean sendMsg(Long senderId, Long receiverId, int msgType, JSONObject msg, StringBuilder error) {
        try {
            MultiValueMap<String, Object> reqParam = new LinkedMultiValueMap<>();
            reqParam.add("from", "" + senderId);
            reqParam.add("ope", 0);
            reqParam.add("to", "" + receiverId);
            reqParam.add("type", msgType);
            reqParam.add("body", msg.toJSONString());

            JSONObject jsonObject = YunXinHelper.exchange(SEND_CHAT_MSG_URL, HttpMethod.POST, reqParam, yunXinConfig);
            Long code = jsonObject.getLong("code");
            if (code == 200L) {
                return true;
            }
            throwExceptionByCode(code, jsonObject);
        } catch (Exception ex) {
            error.append(ex.getMessage());
        }
        return false;
    }

    @Override
    public boolean sendMsgInSession(Long senderId, Long tid, List<Long> receiverIds, int msgType, JSONObject msg, StringBuilder error) {
        try {
            MultiValueMap<String, Object> reqParam = new LinkedMultiValueMap<>();
            reqParam.add("from", "" + senderId);
            reqParam.add("ope", 1);
            reqParam.add("to", "" + tid);
            reqParam.add("type", msgType);
            reqParam.add("body", msg.toJSONString());

            if (CollectionUtils.isEmpty(receiverIds)) {
                //向群中除发送者外的所有成员推送。
                reqParam.add("forcepushall", true);
            } else {
                reqParam.add("forcepushall", false);
                reqParam.add("forcepushlist", receiverIds.stream().map(x -> "" + x).toList());
            }

            JSONObject jsonObject = YunXinHelper.exchange(SEND_CHAT_MSG_URL, HttpMethod.POST, reqParam, yunXinConfig);
            Long code = jsonObject.getLong("code");
            if (code == 200L) {
                return true;
            }
            throwExceptionByCode(code, jsonObject);
        } catch (Exception ex) {
            error.append(ex.getMessage());
        }
        return false;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        yunXinConfig = applicationContext.getBean(IYunXinConfig.class);
    }

    private void throwExceptionByCode(Long code, JSONObject jsonObject) throws Exception {
        String errorInfo = ErrorCode.getErrorMessage(Constant.YUN_XIN_API_VERSION, code);
        if (StringUtils.hasText(errorInfo)) {
            if (code == 414L) {
                errorInfo = MessageFormat.format(errorInfo, jsonObject.get("msg"));
            }
            throw new Exception(errorInfo);
        } else {
            throw new Exception(MessageFormat.format("云信业务错误:{0}", "" + code));
        }
    }
}
